(() => {
    
    
    function setupWebViewJavascriptBridge(callback) {
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'https://__bridge_loaded__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
    }
    
    setupWebViewJavascriptBridge((bridge) => {
        
        /// oc 调用 js start
        bridge.registerHandler('updateUI',(data,callback) => {
//            native_log("开始刷新");
            let pathname = window.location.pathname;
            native_log("解析当前"+window.location.href);
            safeClick("detail-intro-bottom")
            if (safeClick("detail-intro-bottom") == 0) {
                safeClick("menu")
            }
            
            if (window.location.hostname == 'm.baidu.com' && pathname == '/s') {
                novelSources();
            }
            
            if (pathname == '/boxnovel/yuedu/wapcontent') {
                analyseNovelInfo(pathname);
                analyseCurrentChapter();
            } else if (pathname == '/boxnovel/yuedu/wapdetail') {
                analyseNovelInfo(pathname);
                // 打开目录
                safeClick("detail-intro-bottom")
                setTimeout(function () {
                    var els = arrayByClassName("detail-cata-chapter","detail-cata-list");
                    if (els.length > 0) {
                        els[0].click();
                    }
                }, 2000);
                // 刷新 wapcontent
            } else if (pathname) {
                
            }
            callback(document.getElementsByTagName('html')[0].innerHTML);
        });
        bridge.registerHandler('openChapter',(data,callback) => {
            native_log("[openChapter]")
            var res = 0;
            if (data) {
                var index = data["index"];
                var els = arrayByClassName("detail-cata-chapter","detail-cata-list");
                if (els.length > 0) {
                    els[index].click();
                    res = 1;
                }
            }
            callback(res);
        });
        bridge.registerHandler('nextChapter',(data,callback) => {
            native_log("[nextChapter]")
            var res = 0;
            
            callback(res);
        });
        bridge.registerHandler('preChapter',(data,callback) => {
            native_log("[preChapter]")
            var res = 0;
            
            callback(res);
        });
        /// oc 调用 js end
        
        /// js 调用 oc start
        var re = /function\s*(\w*)/i;
        function native_log(param,callback) {
            bridge.callHandler(re.exec(arguments.callee.toString())[1],param,callback);
        }
        function native_analyseNovelInfo(param,callback) {
            bridge.callHandler(re.exec(arguments.callee.toString())[1],param,callback);
        }
        function native_analyseCurrentChapter(param,callback) {
            bridge.callHandler(re.exec(arguments.callee.toString())[1],param,callback);
        }
        function native_getCacheBook(param,callback) {
            bridge.callHandler(re.exec(arguments.callee.toString())[1],param,callback);
        }
        function native_getCacheChapter(param,callback) {
            bridge.callHandler(re.exec(arguments.callee.toString())[1],param,callback);
        }
        /// js 调用 oc end
        
        
        //////////////////////////////////
        function novelSources() {
            native_log('novelSources');
            let articles = document.getElementsByTagName('article')
            for (var i=0; i < articles.length; i++) {
                let article = articles[i];
                let link = article.getAttribute('rl-link-href')
                native_log('url:' + link);
                var request = new XMLHttpRequest();
                request.open("GET", link, true);
                request.onreadystatechange = function() {
                    if (request.readyState === 4 && request.status === 200) {
                        console.log('response:' + request.responseText);
                    }
                };
                request.send();
            }
        }
        /// 解析书详细、目录
        function analyseNovelInfo(pathname) {
            var result = {};
            var url = document.URL;
            var domain = document.domain;
            var title = "";
            var author = "";
            var where = "";
            var logo = "";
            var bookid = "";
            var content = "";
            var bid = "";
            var cid = "";
            native_log("开始："+pathname)
            if (pathname == '/boxnovel/yuedu/wapcontent') {
                cid = getCid(url);
                if (cid == null) return;
                bid = cid.split("|")[0];
                title = textByClassNameSafe("text","title");
                native_log("title："+title)
                author = textByClassNameSafe("author","author-name");
                logo = textByClassNameSafe("logo","detail-header-cont-wrap-img");
                bookid = `<${domain}>${title}(${author})`;
                where = `bid=='${bid}'`;
            } else if (pathname == '/boxnovel/yuedu/wapdetail') {
                title = textByClassNameSafe("detail-header-title-new","title");
                author = textByClassNameSafe("author-name","author");
                native_log("author："+author)
//                logo = document.getElementsByClassName("detail-header-cont-wrap-img")[0].getElementsByTagName("img")[0].src;
//                native_log("logo："+logo)
                bookid = `<${domain}>${title}(${author})`;
                where = `bookid=='${bookid}'`;
            }
            
            native_log(where);
            native_getCacheBook(where,(res) => {
                native_log("native_getCacheBook：查询成功："+JSON.stringify(res));
                var data = res["data"];
                var code = res["code"];
                var book = null;
                if (data.length > 0) {
                    book = data[0];
                    author = book["author"];
                    title = book["title"];
                    domain = book["domain"];
                }
                result = book;
                var isHadCatalogue = book["isHadCatalogue"];
                if (code == 0 && isHadCatalogue == 0) {
                    if (cid == null) {
                        cid = book["cid"];
                        bid = book["bid"];
                    }
                    if (author == "" || author == null) {
                        author = book["author"];
                    }
                    var intro = document.getElementsByClassName("detail-intro-text")[0].textContent;
                    var catalogue = [];
                    //detail-cata-list
                    var els = arrayByClassName("detail-cata-chapter","detail-cata-list");
                    var c_els = document.getElementsByClassName("content");
                    var i = 0;
                    while (i < c_els.length) {
                        content = content + "\n" + c_els[i].textContent;
                        i++;
                    }
                    i = 0;
                    var cur = 0;
                    while (i < els.length) {
                        var c_title = els[i].textContent;
                        var chapterid = `<${domain}>${title}(${author})-${c_title}`;
                        var e = {"name": c_title,"title":title,"author":author,"chapterid":chapterid};
                        if (els[i].classList.contains("read-history")) {
                            e["content"] = content;
                            e["url"] = url;
                            if (cid != null) {
                                e["cid"] = cid;
                            }
                            cur = i;
                        }
                        catalogue.push(e);
                        i++;
                    }
                    bookid = `<${domain}>${title}(${author})`;
                    result = {
                        "bookid":bookid,
                        "bid":bid,
                        "title": title,
                        "logo": logo,
                        "intro": intro,
                        "author": author,
                        "url": url,
                        "catalogue": catalogue,
                        "domain": domain,
                        "url":url
                    };
                    native_analyseNovelInfo(JSON.stringify(result));
                } else {
                    bookid = `<${domain}>${title}(${author})`;
                    result["bookid"] = bookid;
                    native_analyseNovelInfo(JSON.stringify(result));
                }
            });
        }
        /// 解析当前章节
        function analyseCurrentChapter() {
            var url = document.URL;
            native_log("=================\n解析当前章节:"+url);
            let pathname = window.location.pathname;
            var cid = getCid(url);
            var bid = cid.split("|")[0];
            var where = "bid=='"+bid+"'";
            native_getCacheBook(where,(res) => {
                if (res["code"] == 0) {
                    var data = res["data"];
                    var author = null;
                    var content = "";
                    var title = textByClassNameSafe("content-title","title");
                    var domain = document.domain;
                    if (data.length > 0) {
                        var cache = data[0];
                        author = cache["author"];
                        title = cache["title"];
                        domain = cache["domain"];
                    }
                    var name = textByClassNameSafe("chapter-title");
                    var c_els = document.getElementsByClassName("content");
                    
                    var chapterid = `<${domain}>${title}(${author})-${name}`;
                    native_log("开始获取章节内容"+chapterid);
                    native_log("bid:"+bid+",chapterid:"+chapterid);
                    var i = 0;
                    
                    while (i < c_els.length) {
                        content = content + "\n" + c_els[i].textContent;
                        i++;
                    }
                    native_log("已经拿到章节内容"+chapterid+","+content.length)
                    var result = {"content":content,"name":name,"title":title,"domain":domain,"url":url,"cid":cid,"author":author,"chapterid":chapterid};
                    native_analyseCurrentChapter(JSON.stringify(result));
                }
            });
        }
        /// 下一章
        function nextChapter() {
            // tool-bar-item-img next
            safeClick("next")
        }
        /// 上一章
        function preChapter() {
            // tool-bar-item-img prev
            safeClick("prev")
        }
        
        //////////////////////////////////
        function getQueryVariable(url,variable) {
            if (url.indexOf("?") != -1) {
                var params = url.split("?");
                var query = params[1];
                var vars = query.split("&");
                for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    if(pair[0] == variable){return decodeURIComponent(pair[1]);}
                }
            }
            return null;
        }
        function getCid(url) {
            var data = getQueryVariable(url,"data");
            if (data != null) {
                var dataObj = JSON.parse(data);
                return dataObj["cid"];
            }
            return null;
        }
        function textByClassNameSafe(name1,name2) {
            var text = ""
            var name = name1
            try {
                var element = null;
                if (document.getElementsByClassName(name1).length > 0) {
                    element = document.getElementsByClassName(name1)[0];
                } else {
                    if (name2) {
                        element = document.getElementsByClassName(name2)[0];
                    }
                    name = name2;
                }
                text = element.textContent.trim()
            }catch(e){
                text = ""
                native_log("fail[textByClassName]："+name);
            }
            return text;
        }
        function arrayByClassName(name1,name2) {
            var element = [];
            var name = name1
            try {
                if (document.getElementsByClassName(name1).length > 0) {
                    element = document.getElementsByClassName(name1);
                } else {
                    if (name2) {
                        element = document.getElementsByClassName(name2);
                    }
                    name = name2;
                }
            }catch(e){
                native_log("fail[arrayByClassName]："+name);
            }
            return element;
        }
        function safeClick(name) {
            var res = 0
            try {
                document.getElementsByClassName(name)[0].click()
                res = 1
            }catch(e){
                native_log("fail[click]："+name);
                res = 0
            }
            return res
        }
    });
})();
